package com.ezlcp.commons.task;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.ezlcp.commons.listener.NacosDataSourceListener;
import com.ezlcp.commons.utils.NacosUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * @author Elwin ZHANG
 * @description: 仅运行一次的任务<br />
 * @date 2023/6/6 17:33
 */
@Component
@Slf4j
public class RunOnceTask {
    //是否已调用
    private static boolean isAdd = false;

    @Lazy
    @Resource
    private NacosDataSourceListener nacosDataSourceListener;

    @Lazy
    @Resource
    private NacosUtils nacosUtils;

    //程序启动后10秒开始监听Nacos中数据源更新项配置
    @Scheduled(fixedDelayString = "6000000", initialDelay = 10000)
    public void setNacosListener() throws NacosException {
        if (isAdd) {
            return;
        }
        ConfigService service = nacosUtils.getConfigService("");
        //先根据配置初始化加载全部数据源
        var config=service.getConfig(NacosUtils.KEY_OF_DATASOURCE,"",NacosUtils.READ_TIME_OUT_MS);
        nacosDataSourceListener.refreshDatasource(config,true);
        //监听配置项
        service.addListener(NacosUtils.KEY_OF_DATASOURCE, "", nacosDataSourceListener);
        isAdd = true;
    }
}
